<template>
  <div>
    <!-- 表格开始  -->
    <div v-if="showTab">
      <!--<div class="warn">
        <el-alert
          title="配置须知"
          type="info"
          :description="message"
          show-icon>
        </el-alert>
      </div>
      <searIte :arr="list"></searIte>-->
      <el-table :data="tbinfo" style="width: 100%;text-align: center" stripe max-height="500px">
        <el-table-column v-for="th in thinfo"
                         :show-overflow-tooltip="true"
                         header-align="center"
                         :key = "th.key"
                         :prop="th.key"
                         :label="th.value">
        </el-table-column>
        <el-table-column :render-header="renderHeader" width="210" fixed="right" header-align="center">
          <template scope="scope">
            <el-tooltip effect="light" content="复制为新增配置" placement="left" :enterable="false">
              <el-button type="primary" icon="plus" size="small"
                         @click.native.prevent="showCopyItemDialog(tbinfo[scope.$index])"></el-button>
            </el-tooltip>
            <el-tooltip effect="light" content="编辑" placement="top" :enterable="false">
              <el-button type="primary" icon="edit" size="small"
                         @click="showEditItemDialog(tbinfo[scope.$index])"></el-button>
            </el-tooltip>
            <el-tooltip effect="light" content="详细信息" placement="top" :enterable="false">
              <el-button type="primary" size="small" icon="search"
                         @click="showLookItemDialog(tbinfo[scope.$index])"></el-button>
            </el-tooltip>
            <el-tooltip effect="light" content="谨慎操作" placement="top" :enterable="false">
              <el-button size="small" type="danger" icon="delete" @click="deleteItem(tbinfo[scope.$index])">
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <transition name="el-zoom-in-center">
      <div v-show="!showTab">
        <welcome></welcome>
      </div>
    </transition>
    <dia-ite ref="dialog" :fields="dialogData" :type="dialogType" :isReadOnly="isReadOnly" @save="saveItem"
             :fuctype="fuctype"></dia-ite>
    <el-dialog title="新增配置项" :visible.sync="dialogFormVisible" size="" top="10%">
      <el-form>
        <el-row :gutter="24">
          <el-col :span="24" v-for="f in fields" :key="f.id" style="margin-bottom: 20px;">
            <div class="input-group" v-if="f.type == '1'">
              <span class="input-group-addon" style="background-color: #324057;color: #e6f1fe;">{{f.description}}</span>
              <el-input :placeholder="f.tip" :id="f.id" :keys="f.id" type="textarea"
                        autosize></el-input>
            </div>
            <div class="input-group" v-else="">
              <span class="input-group-addon" style="background-color: #EFF2F7">{{f.description}}</span>
              <el-input :placeholder="f.tip" :id="f.id" :keys="f.id" type="textarea"
                        autosize></el-input>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addItem">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style>
  .warn {
    text-align: center;
    margin-bottom: 5px;
  }
</style>

<script>
  import {mapState} from 'vuex';
  import searIte from "../components/search.vue";
  import diaIte from "../components/dialog.vue";
  import welcome from "./welcome.vue";
  import fetch from "../../store/uacc_api";
  export default {
    components: {
      searIte,
      diaIte,
      alert,
      welcome
    },
    computed: {
      structObj: function () {
        let obj = JSON.parse(JSON.stringify(this.$store.state.currentStructs));
        return obj;
      },
      thinfo: function () {
        let head = [];
        //每一行数据展示的列数量
        //let max = 7;
        if (this.structObj) {
          //let count = 0;
          for (let pro in this.structObj.titleFields) {
            //if (count < max) {
            let str = {key: pro, value: this.structObj.titleFields[pro]};
            head.push(str);
            //}
            //count++;
          }
          if(head.length == 0){
            head.push({key:'',value:''});
          }
          return head;
        } else {
          return head;
        }
      },
      tbinfo: function () {
        let body = [];
        if (this.structObj) {
          if (this.structObj.hasOwnProperty('items')) {
            for (let item of this.structObj.items) {
              item.itemMap.uaccItemId = item.id;
              item.itemMap.uaccTreeNodeId = item.treeNodeId;
              item.itemMap.uaccConfigStructId = item.configStructId;
              body.push(item.itemMap);
            }
          }
          return body;
        } else {
          return body;
        }
      },
      showTab: function () {
        if (this.$store.state.currentStructs) {
          if (this.$store.state.currentStructs.hasOwnProperty('id')) {
            return true;
          } else {
            return false;
          }
        } else {
          return false;
        }
      }
    },
    methods: {
      renderHeader(createElement) {
        return createElement(
          'div',
          {
            'class': 'renderTableHead'
          },
          [
            createElement('el-button', {
                attrs: {type: 'success', plain: true, size: 'small'},
                on: {click: this.showAddItemDialog}
              }, ['添加']
            ),
            createElement('el-button', {
                attrs: {type: 'danger', plain: true, size: 'small'},
                on: {click: this.push}
              }, ['推送']
            )
          ]
        );
      },
      push(){
        let me = this;
        fetch.pushConfig({nodeId: this.$store.state.currentNode.id}).then(function (res) {
          if (res.success) {
            me.$message({
              showClose: true,
              type: 'success',
              message: '推送成功'
            });
          } else {
            me.$message({
              showClose: true,
              message: res.errorMessage,
              type: 'error'
            });
          }
        })
      },
      showAddItemDialog(){
        this.queryFieldsOfStruct();
        this.dialogFormVisible = true;
      },
      queryFieldsOfStruct(){
        let me = this;
        let param = {structId: this.structObj.id};
        fetch.queryFieldsOfStruct(param).then(function (res) {
          if (res.success) {
            me.fields = res.data;
          } else {
            me.$message({
              showClose: true,
              message: res.errorMessage,
              type: 'error'
            });
          }
        })
      },
      addItem(){
        let param = {treeNodeId: this.structObj.nodeId, configStructId: this.structObj.id};
        var itemmap = {};
        for (let field of this.fields) {
          let div = document.getElementById(field.id);
          let text = div.getElementsByTagName("textarea")[0].value;
          itemmap[field.name] = text;
        }
        param.itemMap = itemmap;
        let encodeparam = {'data': encodeURIComponent(JSON.stringify(param))};
        this.addConfigItem(encodeparam);
      },
      //查看item信息
      showLookItemDialog(val){
        let tmp = {id: val.uaccItemId, treeNodeId: val.uaccTreeNodeId, configStructId: val.uaccConfigStructId};
        let itemMap = [];
        for (let k in this.structObj.titleFields) {
          let n = this.structObj.titleFields[k];
          let obj;
          if (val.hasOwnProperty(k)) {
            if (this.contains(this.structObj.keys, k)) {
              obj = {name: n, value: val[k], key: k, isKey: true, tip: ''};
            } else {
              obj = {name: n, value: val[k], key: k, isKey: false, tip: ''};
            }
          } else {
            if (this.contains(this.structObj.keys, k)) {
              obj = {name: n, value: '', key: k, isKey: true, tip: ''};
            } else {
              obj = {name: n, value: '', key: k, isKey: false, tip: ''};
            }
          }
          itemMap.push(obj);
        }
        tmp.itemMap = itemMap;
        this.dialogData = tmp;
        this.dialogType = '';
        this.isReadOnly = true;
        this.$refs.dialog.show();
      },
      showCopyItemDialog(val){
        let tmp = {id: val.uaccItemId, treeNodeId: val.uaccTreeNodeId, configStructId: val.uaccConfigStructId};
        let itemMap = [];
        for (let k in this.structObj.titleFields) {
          let n = this.structObj.titleFields[k];
          let obj;
          if (val.hasOwnProperty(k)) {
            if (this.contains(this.structObj.keys, k)) {
              obj = {name: n, value: '', key: k, isKey: true, tip: this.structObj.fieldTips[k]};
            } else {
              obj = {name: n, value: val[k], key: k, isKey: false, tip: this.structObj.fieldTips[k]};
            }
          } else {
            if (this.contains(this.structObj.keys, k)) {
              obj = {name: n, value: '', key: k, isKey: true, tip: this.structObj.fieldTips[k]};
            } else {
              obj = {name: n, value: '', key: k, isKey: false, tip: this.structObj.fieldTips[k]};
            }
          }
          itemMap.push(obj);
        }
        tmp.itemMap = itemMap;
        this.dialogData = tmp;
        this.dialogType = 'confirm';
        this.isReadOnly = false;
        this.fuctype = 'copy';
        this.$refs.dialog.show();
      },
      showEditItemDialog(val){
        let tmp = {id: val.uaccItemId, treeNodeId: val.uaccTreeNodeId, configStructId: val.uaccConfigStructId};
        let itemMap = [];
        for (let k in this.structObj.titleFields) {
          let n = this.structObj.titleFields[k];
          let obj;
          if (val.hasOwnProperty(k)) {
            if (this.contains(this.structObj.keys, k)) {
              obj = {name: n, value: val[k], key: k, isKey: true, tip: this.structObj.fieldTips[k]};
            } else {
              obj = {name: n, value: val[k], key: k, isKey: false, tip: this.structObj.fieldTips[k]};
            }
          } else {
            if (this.contains(this.structObj.keys, k)) {
              obj = {name: n, value: '', key: k, isKey: true, tip: this.structObj.fieldTips[k]};
            } else {
              obj = {name: n, value: '', key: k, isKey: false, tip: this.structObj.fieldTips[k]};
            }
          }
          itemMap.push(obj);
        }
        tmp.itemMap = itemMap;
        this.dialogData = tmp;
        this.dialogType = 'confirm';
        this.isReadOnly = false;
        this.fuctype = 'change';
        this.$refs.dialog.show();
      },
      //新增dialog保存处理(子组件传递参数)
      saveItem(val){
        let fields = val.fields;
        let param = {treeNodeId: fields.treeNodeId, configStructId: fields.configStructId};
        var itemmap = {};
        for (let i = 0; i < fields.itemMap.length; i++) {
          let field = fields.itemMap[i]
          itemmap[field.key] = field.value;
        }
        param.itemMap = itemmap;
        //编辑窗口调用后台接口
        if (this.trim(val.fuctype) === 'change') {
          param.id = fields.id;
          let encodeparam = {'data': encodeURIComponent(JSON.stringify(param))};
          this.editConfigItem(encodeparam);
        } else if (this.trim(val.fuctype) === 'copy') {
          //复制新增窗口调用后台接口
          let encodeparam = {'data': encodeURIComponent(JSON.stringify(param))};
          this.addConfigItem(encodeparam);
        }
      },
      trim(param) {
        let vRet;
        if ((vRet = param) == '') {
          return vRet;
        }
        while (true) {
          if (vRet.indexOf(' ') == 0) {
            vRet = vRet.substring(1, parseInt(vRet.length));
          } else if ((parseInt(vRet.length) != 0) && (vRet.lastIndexOf(' ') == parseInt(vRet.length) - 1)) {
            vRet = vRet.substring(0, parseInt(vRet.length) - 1);
          } else {
            return vRet;
          }
        }
      },
      contains(arr, obj) {
        var i = arr.length;
        while (i--) {
          if (this.trim(arr[i]) === this.trim(obj)) {
            return true;
          }
        }
        return false;
      },
      deleteItem(val) {
        let me = this;
        this.$confirm('该操作将会删除该配置，是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          this.tableLoading = true;
          fetch.deleleConfigItem({nodeId: me.structObj.nodeId, itemId: val.uaccItemId}).then(function (res) {
            if (res.success) {
              me.$message({
                showClose: true,
                type: 'success',
                message: '删除成功'
              });
              me.$emit('refshStruct');
            } else {
              console.error(res);
              me.$message({
                showClose: true,
                message: res.errorMessage,
                type: 'error'
              })
            }
            me.tableLoading = false;
          }).catch(function () {
            me.tableLoading = false;
          })
        })
      },
      addConfigItem(param) {
        this.tableLoading = true;
        let me = this;
        fetch.addConfigItem(param).then(function (res) {
          me.dialogFormVisible = false;
          if (res.success) {
            me.$message({
              showClose: true,
              type: 'success',
              message: '添加成功'
            });
            //刷新当前配置集数据
            me.$emit('refshStruct');
          } else {
            me.$message({
              showClose: true,
              message: res.errorMessage,
              type: 'error'
            });
          }
          me.tableLoading = false;
        }).catch(function () {
          me.tableLoading = false;
        })
      },
      editConfigItem(param) {
        this.tableLoading = true;
        let me = this;
        fetch.updateConfigItem(param).then(function (res) {
          if (res.success) {
            me.$message({
              showClose: true,
              type: 'success',
              message: '修改成功'
            });
            //刷新当前配置集数据
            me.$emit('refshStruct');
          } else {
            me.$message({
              showClose: true,
              type: 'error',
              message: '修改失败:  ' + res.errorMessage
            });
          }
          me.tableLoading = false;
        }).catch(function () {
          me.tableLoading = false;
        })
      }
    },
    data: function () {
      return {
        fuctype: '',
        dialogFormVisible: false,
        tableLoading: false,
        dialogData: {},
        isReadOnly: true,
        fields: [],
        dialogType: 'confirm',
        itemData: {},
      }
    }
  }
</script>
